package com.by.service.impl;


import com.by.bean.Supplier;
import com.by.bean.User;
import com.by.bean.UserType;
import com.by.common.bean.PageBean;
import com.by.common.bean.ResultBean;
import com.by.common.crud.BaseServiceImpl;
import com.by.common.ex.BusinessException;
import com.by.common.utils.Assert;
import com.by.mapper.SupplierContactMapper;
import com.by.mapper.SupplierMapper;
import com.by.mapper.UserMapper;
import com.by.query.SupplierQuery;
import com.by.service.SupplierService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.Serializable;
import java.util.List;

@Service
public class SupplierServiceImpl extends BaseServiceImpl<Supplier, SupplierMapper> implements SupplierService {


    @Autowired
    UserMapper userMapper;

    @Autowired
    SupplierContactMapper supplierContactMapper;
    @Override
    public int save(Supplier entity) {
        //检查用户是否存在
        int c = userMapper.queryUserByUserName(entity.getAccount());
        if (c >0)
            throw new BusinessException("该账号已存在！！");
        //保存用户
        User user =new User(entity.getAccount(),entity.getPassword(), UserType.SUPPLIER_USER);
        int rs =userMapper.save(user);
        Assert.isZero(rs,"保存用户失败");
        //设置联系人的供应商id
        entity.getContact().setSupplierId(user.getId());
        //保存供应商联系人
        rs=supplierContactMapper.save(entity.getContact());
        Assert.isZero(rs,"保存供应商联系人失败");
        //设置供应商id
        entity.setId(user.getId());
        return super.save(entity);
    }
    @Override
    public PageBean query(SupplierQuery query) {
        //分页查询
        PageHelper.startPage(query.getPage(), query.getPageSize());//后面紧跟查询
        List list = baseMapper.query(query);
        PageInfo info = new PageInfo(list);
        return new PageBean(query.getPage(), query.getPageSize(), info.getTotal(), list);
    }

    @Transactional
    public int delete(Serializable id) {
        //删除用户
        int rs= userMapper.delete(id);
        Assert.isZero(rs,"删除用户失败");
        return super.delete(id);
    }


}
